#!/bin/bash


DNS1_IP="223.5.5.5"
DNS2_IP="223.6.6.6"


function select_network_interface() {
    # 获取到所有的网卡并且将这些网卡作为变量NETWORK_NAME的选项选择后赋值给NETWORK_NAME
    readarray -t NETWORK_OPTIONS < <(ip link show | awk -F: '$0 !~ "lo|vir|docker|br-|veth|wl|^[^0-9]"{print $2}')
    # NETWORK_OPTIONS=("${NETWORK_OPTIONS[@]}")
    PS3="请选择要配置的网络接口："
    select NETWORK_NAME in "${NETWORK_OPTIONS[@]}"; do
        if [[ -n "$NETWORK_NAME" ]]; then
            
            break
        else
            return -1
        fi
    done
    NETWORK_NAME=$(echo "$NETWORK_NAME" | xargs)
    echo "$NETWORK_NAME"
}

function get_current_ip() {
    local NETWORK_NAME="$1"
    # 获取当前主机的ip
    ip=$(ip addr | grep ${NETWORK_NAME} | grep inet | grep -v inet6 | awk '{print $2}' | cut -d/ -f1)
    echo "$ip"
}

sudo apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y

NETWORK_NAME=$(select_network_interface)

# 自动获取当前默认网关
GATEWAY_IP=$(ip route show default dev "${NETWORK_NAME}" | awk '{print $3}')
echo ${GATEWAY_IP}
if [[ -n "$GATEWAY_IP" ]]; then
    echo "已自动获取到网关地址: $GATEWAY_IP"
else
    echo "未找到默认网关，请检查网络连接。"
    exit 1
fi

# 使用函数 get_current_ip 获取当前服务器的ip地址， 让用户选择是否使用这个ip如果用户选择否那么让用户手动输入一个ip地址
# 获取当前服务器IP
CURRENT_IP=$(get_current_ip "${NETWORK_NAME}")

# 提示用户是否使用当前IP
read -p "检测到当前IP为: ${CURRENT_IP}，是否使用此IP？(y/n): " USE_CURRENT_IP

if [[ "$USE_CURRENT_IP" =~ ^[Nn]$ ]]; then
    read -p "请输入新的IP地址: " CURRENT_IP
fi

echo "最终使用的IP地址为: ${CURRENT_IP}"


NETPLAN_FILE=""
for f in "50-cloud-init.yaml" "00-installer-config.yaml"; do
    if [[ -f "/etc/netplan/$f" ]]; then
        NETPLAN_FILE="/etc/netplan/$f"
        break
    fi
done

if [[ -z "$NETPLAN_FILE" ]]; then
    # 如果都没找到，就取第一个 .yaml 文件
    NETPLAN_FILE=$(find /etc/netplan/ -maxdepth 1 -name "*.yaml" | head -n1)
fi

if [[ -z "$NETPLAN_FILE" ]]; then
    echo "未找到可用的 netplan 配置文件。"
    exit 1
fi

sudo tee "${NETPLAN_FILE}" > /dev/null << EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    ${NETWORK_NAME}:
      dhcp4: false
      dhcp6: false
      addresses:
        - ${CURRENT_IP}/24
      routes:
        - to: default
          via: ${GATEWAY_IP}
      nameservers:
          addresses: [${DNS1_IP}, ${DNS2_IP}]
EOF

sudo netplan apply